import { defineStore } from "pinia";
import {
  loginApi,
  logoutApi,
  getUserPermissionByToken,
  getUserInfo,
} from "../api/user";
import { ElMessage } from "element-plus";
import router from "../router";

export const useUserStore = defineStore("user", {
  state: () => ({
    token: localStorage.getItem("token") || "",
    userInfo: (() => {
      const stored = localStorage.getItem("userInfo");
      if (stored) {
        try {
          return JSON.parse(stored);
        } catch {
          return null;
        }
      }
      return null;
    })(),
    accessRoutes: JSON.parse(
      localStorage.getItem("accessRoutes") || "[]"
    ) as any,
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    getToken: (state) => state.token,
    getUserInfo: (state) => {
      if (state.userInfo && typeof state.userInfo === 'string') {
        try {
          return JSON.parse(state.userInfo);
        } catch {
          return null;
        }
      }
      return state.userInfo;
    },
    getAccessRoutes: (state) => state.accessRoutes,
  },

  actions: {
    // 设置token
    setToken(token: string) {
      this.token = token;
      localStorage.setItem("token", token);
    },

    // 设置用户信息
    setUserInfo(userInfo: any) {
      this.userInfo = userInfo;
      localStorage.setItem("userInfo", JSON.stringify(userInfo));
    },

    // 登录
    async login(params: any) {
      try {
        // await loginApi(params).then((res: any) => {
        //   this.setToken(res.result.token);
        //   this.setUserInfo(res.result.userInfo);
        // });
        this.setToken('eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImxvZ2luX3VzZXJfa2V5IjoiNWI1MmE0MmItMjg1Ni00ZDRmLTg4ZWEtNDUyM2I4OWI5OWI2In0.pWLSPm2kxgpyMLinRHYEYhyRRo3uq8WIiAu7ms9vWsDBUj08Rms56YayF5YXimGpRzPJN84GZGODk3Sqja9vag')
        ElMessage.success("登录成功");
        router.push({path:'/'})
      } catch (error) {
        throw error;
      }
    },

    // 清除token
    clearToken() {
      this.token = "";
      localStorage.removeItem("token");
    },

    // 清除用户信息
    clearUserInfo() {
      this.userInfo = "";
      localStorage.removeItem("userInfo");
    },

    // 清除访问路由
    clearAccessRoutes() {
      this.accessRoutes = [];
      localStorage.removeItem("accessRoutes");
    },

    // 登出
    async logout() {
      try {
        await logoutApi().then((res: any) => {
          ElMessage.success(res.message);
        });
      } catch (error) {
        throw error;
      } finally {
        this.clearToken();
        this.clearUserInfo();
        this.clearAccessRoutes();
      }
    },
  },
});
